<template>
	<div>
		<div class="search" >
			<input class="search-input" v-model="keyWord" type="text" placeholder="请输入城市名称" />
		</div>
		<div class="search-alert" v-show="keyWord" ref="search">
			<ul>
				<li v-for="item of list" :key="item.id" class="search-item border-bottom" @click="handleCilckChange(item.name)" >{{item.name}}</li>
				<li class="search-item border-bottom" v-show="hasNoData">没有找到匹配内容</li>
			</ul>
		</div>
	</div>
</template>

<script>
	import Bscroll from 'better-scroll'
	import { mapMutations } from 'vuex'
	export default {
		name: 'citySearch',
		data () {
			return {
				keyWord:'',
				list:[],
				timer:null
			}
		},
		props: {
			cities:Object
		},
		computed: {
			hasNoData () {
				return !this.list.length
			}
		},
		methods: {
			handleCilckChange (val) {
				//this.$store.dispatch('changeCity',val)
				//this.$store.commit('changeCity',val)
				this.changeCity(val)
				//页面跳转
				this.$router.push('/')
			},
			...mapMutations(['changeCity'])
		},
		watch: {
			keyWord () {
				if(this.timer){
					clearTimeout(this.timer)
				}
				if(!this.keyWord){
					this.list=[]
					return
				}
				this.timer=setTimeout(()=>{
					const result=[];
					for(let i in this.cities){
						this.cities[i].forEach((value)=>{
							if(value.spell.indexOf(this.keyWord)>-1||
								value.name.indexOf(this.keyWord)>-1){
									result.push(value)
								}
						})
					}
					this.list=result
				},100)
			}
		},
	mounted ()　{
			this.scroll=new Bscroll(this.$refs.search, {click: true})
		},
	}
</script>

<style lang="stylus" scoped>
	@import "~styles/varibles.styl";
	.search
		height:.72rem
		background:$bkColor
		padding:.1rem
		.search-input
			height:.7rem
			line-height:.7rem
			box-sizing:border-box
			width:100%
			padding:0 .1rem
			color:#888
			border-radius:.06rem
			border-style:none
			text-align:center
	.search-alert
		position:absolute
		overflow:hidden
		top:1.7rem
		left:0
		right:0
		bottom:0
		background:#eee
		z-index:1
		.search-item
			line-height:.62rem
			background:#fff
			color:#666
			padding-left:.2rem
</style>